import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:tx_live_plugin/tx_constant.dart';

///视频聊天会议
class TxLiveChat extends StatelessWidget {

  final ChatController? controller;
  final ChatCallback? callback;

  const TxLiveChat({Key? key, this.controller, this.callback}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (Platform.isAndroid) return _androidWidget();
    return Center(
      child:
          Text("current platform ${Platform.operatingSystem} is not support"),
    );
  }

  ///Android显示推流控件
  Widget _androidWidget() {
    return AndroidView(
      viewType: platformFactory,
      creationParams: const {ViewType.key:ViewType.chat},
      creationParamsCodec: const StandardMessageCodec(),
      onPlatformViewCreated: onPlatformViewCreated,
    );
  }

  void onPlatformViewCreated(int id) {
    MethodChannel _channel = MethodChannel("${Channel.chatChannel}$id")
      ..setMethodCallHandler(_handler);
    controller?._setChannel = _channel;
  }

  ///处理原生发过来的消息
  Future _handler(MethodCall call) async {
    var method = call.method;
    var arg = call.arguments;
    switch (method) {
      case ChatBack.toast:
        if (arg is String) {
          callback?.toast(arg);
          return;
        }
        _error(PushBack.toast);
        break;
      case ChatBack.fail:
        if (arg is String) {
          callback?.fail(arg);
          return;
        }
        _error(ChatBack.fail);
        break;
      case ChatBack.notifyRoomCreate:
        if (arg is String) {
          callback?.notifyRoomCreate(arg);
          return;
        }
        _error(ChatBack.notifyRoomCreate);
        break;
      case ChatBack.startTime:
        bool intoRoom = arg?[ChatKey.intoRoom] ?? false;
        int timeCount = arg?[ChatKey.timeCount] ?? 0;
        callback?.startTime(intoRoom, timeCount);
        break;
    }
  }

  _error(String name, {dynamic data}) {
    print("methodName $name is error, arguments $data");
  }
}

///原生通知 flutter进行处理
abstract class ChatCallback {
  ///一些通知
  toast(String? message) {}

  ///视频会议："进入房间失败"、"创建者已结束会议"，需要关闭页面
  fail(String? message) {}

  ///通知视频房间会议 创建成功，可以直接toast提示
  notifyRoomCreate(String? toast) {}

  ///开始计时器，
  ///intoRoom是否进入房间，false代表尝试进入房间，可以计时1分钟后提示进入房间失败，关闭页面，如果收到true则停止该计时；
  ///true代表成功进入房间，计时30分钟后，退出房间
  startTime(bool? intoRoom,int? secondTime) {}
}

///视频会议控制
class ChatController extends ChangeNotifier {
  MethodChannel? _channel;

  set _setChannel(MethodChannel channel) => _channel = channel;

  ///通过channel通知原生处理数据
  _notifyChannel(String methodName, {dynamic data}) {
    final c = _channel;
    if (c == null) {
      print("tx_live_plugin ChatController' channel is null，cannot use methodName $methodName");
      return -1;
    }
    return c.invokeMethod(methodName, data);
  }

  ///创建会议或进入会议房间
  ///返回true表示开始
  startChat({int? sdkAppId, int? roomId, String? userId, String? userSign}) {
    return _notifyChannel(ChatMethod.startChat, data: {
      ChatKey.sdkAppId: sdkAppId,
      ChatKey.roomId: roomId,
      ChatKey.userId: userId,
      ChatKey.userSign: userSign,
    });
  }

  ///结束视频 退出房间
  stopChat() {
    return _notifyChannel(ChatMethod.stopChat);
  }

  ///暂停
  onPause() {
    return _notifyChannel(ChatMethod.onPause);
  }

  ///重新唤起
  onResume() {
    return _notifyChannel(ChatMethod.onResume);
  }

  ///销毁
  onDestroy() {
    return _notifyChannel(ChatMethod.onDestroy);
  }

  ///是否 会议房间创建中
  isCreating() {
    return _notifyChannel(ChatMethod.isCreating);
  }

  ///是否 开启音频
  isOpenAudio() {
    return _notifyChannel(ChatMethod.isOpenAudio);
  }

  ///开启/关闭 切换音频
  switchAudio() {
    return _notifyChannel(ChatMethod.switchAudio);
  }

  @override
  void dispose() {
    super.dispose();
    onDestroy();
  }
}
